package com.atzxh.heima.netty.c3;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

/**
 * @author 小红同学
 * @date 2023-12-17-21:03
 * @description
 */
@Slf4j
public class EventLoopServer {
    public static void main(String[] args) {
        // 细分2：如果执行耗时操作，可单独创建一个group
        DefaultEventLoopGroup group = new DefaultEventLoopGroup();

        new ServerBootstrap()
                // 细分1：使用两个group，一个负责accept事件，一个负责read事件
                .group(new NioEventLoopGroup(1), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                      @Override
                      protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                          nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                          nioSocketChannel.pipeline().addLast("head-1", new ChannelInboundHandlerAdapter() {
                              @Override
                              public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                  ByteBuf byteBuffer = (ByteBuf) msg;
                                  log.debug(byteBuffer.toString(Charset.defaultCharset()));
                                  // 执行下一个handler
                                  ctx.fireChannelRead(msg);
                              }
                          }).addLast(group, "head-2", new ChannelInboundHandlerAdapter() {
                              @Override
                              public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                  ByteBuf byteBuffer = (ByteBuf) msg;
                                  log.debug(byteBuffer.toString(Charset.defaultCharset()));

                                  // 传回客户端
                                  ByteBuf buffer = ctx.alloc().buffer();
                                  buffer.writeBytes(byteBuffer);
                                  ctx.writeAndFlush(buffer);
                              }
                          });
                      }
                  }
                )
                .bind(8088);
    }
}
